package com.example.demo.service;

import com.example.demo.exception.BusinessException;
import com.example.demo.exception.ResourceNotFoundException;
import com.example.demo.model.Course;
import com.example.demo.model.Order;
import com.example.demo.repository.CourseRepository;
import com.example.demo.repository.StudentCourseRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@RequiredArgsConstructor
public class EnrollmentService {
    private final CourseRepository courseRepository;
    private final StudentCourseRepository studentCourseRepository;
    private final OrderService orderService;


    @Transactional
    public Order enrollCourse(Long studentId) {
        Long courseId = enrollRequest.getCourseId();

        // 检查课程是否存在
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new ResourceNotFoundException("Course not found"));

        // 检查课程是否已发布
        if (course.getStatus() != Course.CourseStatus.PUBLISHED) {
            throw new BusinessException("Course is not available for enrollment");
        }

        // 检查是否已选课
        if (studentCourseRepository.existsByStudentIdAndCourseId(studentId, courseId)) {
            throw new BusinessException("You have already enrolled in this course");
        }

        // 创建订单
        Order order  = orderService.createOrder(studentId, courseId, course.getPrice());

        // 如果是免费课程，直接确认选课
        if (course.getPrice() == null || course.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            confirmEnrollment(studentId, courseId, order .getId());
            order .setStatus(Order.OrderStatus.PAID.name());
        }

        return order ;
    }

    @Transactional
    public void confirmEnrollment(Long studentId, Long courseId, Long orderId) {
        // 更新订单状态为已支付
        orderService.updateOrderStatus(orderId, Order.OrderStatus.PAID);

        // 添加选课记录
        StudentCourse studentCourse = new StudentCourse();
        User student = new User();
        student.setId(studentId);
        Course course = new Course();
        course.setId(courseId);

        studentCourse.setStudent(student);
        studentCourse.setCourse(course);
        studentCourseRepository.save(studentCourse);
    }

    @Transactional
    public void cancelEnrollment(Long studentId, Long courseId) {
        // 检查是否已选课
        if (!studentCourseRepository.existsByStudentIdAndCourseId(studentId, courseId)) {
            throw new BusinessException("You are not enrolled in this course");
        }

        // 删除选课记录
        studentCourseRepository.deleteByStudentIdAndCourseId(studentId, courseId);

        // 更新相关订单状态为已取消
        orderService.cancelOrderByStudentAndCourse(studentId, courseId);
    }
}